<?php

	//while editing system..
	if(!true){
		if(!checkQualified(4000)) {
			print "Sorry.. The scheduling system is being worked on.";
			return;
		} else {
			alertText("The scheduling system is unavailable to all users!");
		}
	}

	//check to see if we've already connected to the mysql db..
	if(!is_resource($link)) {
		  require("/export/www/transportation/includes/variables.php");
			//require(SESSION_HANDLER_FILE);
			//session_start();
		  //session_start();
		  define(LOGGEDIN,false);
	}

	// THIS section allows an am to print out a full group schedule
	if(isset($_REQUEST['group_id']) && isset($_REQUEST['fullsize'])) {
		/*if(!checkQualified(1000)) {
			print "You are not authorized to view this.";
			exit;
		}*/
		$group = $_REQUEST['group_id'];
		$sql = 'SELECT `t_sched_groups`.`description` AS groupdesc, `t_sched_main`.*'
        . ' FROM `t_sched_groups`,`t_sched_main`'
        . ' WHERE `t_sched_groups`.`group_id` = ' . $group
        . ' AND `t_sched_groups`.`group_id` = `t_sched_main`.`group_id`'
        . ' ORDER BY `t_sched_main`.`order` ';
		$query = mysql_query($sql);
		
		print "<html>
	<head>
		<title>UCTS Schedule</title>
			<style type='text/css'>
			<!--
				* {
					font-family: Verdana, Tahoma;
					font-size: 12px;
				}
				@page normal {
					size: landscape;
					margin: 1in;
				}
				body { page: normal; }
				.title {
					font-size: 20px;
					font-weight: bold;
				}
				.sub-title {
					font-size: 16px;
					font-weight: bold;
				}
			-->
			</style>
		</head>
		<body >\n";
		$newPageStyle = "";
		//clear driver_id to prevent shifts from being highlighted
		$old_driver_id = $_SESSION['driver_id'];
		$_SESSION['driver_id'] = 0;
		while($schedule_loop = mysql_fetch_assoc($query)) {
			print "<div class='title' style='" . $newPageStyle . " text-align:center;'>" . $schedule_loop['groupdesc'] . "</div>\n";
			print "<div class='sub-title' style='text-align: center;'>" . $schedule_loop['description'] . "</div>\n";
			generateShiftBoard($schedule_loop['table_id']);
			$newPageStyle = "page-break-before: always;";
		}
		//reset driver_id
		$_SESSION['driver_id'] = $old_driver_id;
		print "</body>
				</html>\n";
		exit;		
	} //end group schedule if

	// THIS WHOLE SECTION IS ONLY FOR SIGNUPS.. This script has been designed
	// to allow inclusion without outputting anything to allow for the use of
	// the generateShiftBoard function..

	if(isset($_REQUEST['sched'])) { print "<h1 align='center'>Signups</h1>\n"; }

	//check if exclusion is active
	if(ENFORCE_EXCLUSION && exclusionActiveDriver($_SESSION['driver_id']))
		alertText("You currently have exclusive access to a schedule!");

	//exclusive access!!! oooooo.. cool!!!
	if(isset($_REQUEST['exclusive']) && ENFORCE_EXCLUSION) {
		//they are trying to gain exclusive access to a schedule
		$signup_id = $_REQUEST['exclusive'];
		$excluseAccess = exclusiveAccess($signup_id);
		if(excluseAccess) {
			//they can get access.. lets give it to them.
			$result = mysql_query(sprintf("UPDATE `t_sched_signups` SET `exclusive` = 1 WHERE `signup_id` = %s LIMIT 1", quote_smart($signup_id)));
			if(mysql_affected_rows() == 1) {
				//updated them, lets set them as exclusive in the group
				//grab signup data
				$signupinfo = mysql_query(sprintf("SELECT * FROM `t_sched_signups` WHERE `signup_id` = %s LIMIT 1",quote_smart($signup_id)));
				$data = mysql_fetch_assoc($signupinfo);
				$result = mysql_query(sprintf("UPDATE `t_sched_groups` SET `exclusive_lock_driver` = %s, `exclusive_lock_expire` = %s WHERE `group_id` = %s",quote_smart($_SESSION['driver_id']),quote_smart($excluseAccess + time()),quote_smart($data['group_id'])));
				if(mysql_affected_rows() == 1) {
					?><div style="margin:20px; background-color:#FFFFCC; border: 1px solid #FFFF00; padding: 10px; text-align:center; font-weight: bold;"><?= displayIcon(ICON_ACCEPT) ?> You have been granted exclusive access until <?php  print date("g:i a", time() + $excluseAccess); ?>.</div><?php  
				} else {
					errorText("An error occurred trying to grant the exclusive lock.");
				}
			} else {
				errorText("An error occurred trying to update exclusion variable in signup slot.");
			}
		} else {
			errorText("Exclusive Access Denied.");
		}
	}
			

  $driver = $_SESSION['driver_id'];
  if($_REQUEST['sched'] == 'pick_group') {
    //query all schedules not archived..
	$sql = mysql_query("SELECT * FROM `t_sched_groups` WHERE `status` >= 0 ORDER BY `status` DESC, `group_id` DESC");
    while($row = mysql_fetch_assoc($sql)) {
	  $description = $row['description'];
	  $group = $row['group_id'];
	  $driver = $_SESSION['driver_id'];
	  
	  unset($signup_data);
	  //grab earliest signup time associated with this group
	  $signup_result = mysql_query("SELECT * FROM `t_sched_signups` WHERE `group_id` = $group AND `driver_id` = $driver ORDER BY `date` ASC, `time` ASC LIMIT 1");
	  //if they have a time, store it
	  if(mysql_num_rows($signup_result)) {
	  	$signup_data = mysql_fetch_assoc($signup_result);
		$date = $signup_data['date'];
		$time = $signup_data['time'];
		$signupid = $signup_data['signup_id'];
		$hasSignupTime = true;
		if(DEBUG) alertText("Driver has a signup time (" . $signupid . ").");
	  } else {
	  	$hasSignupTime = false;
		if(DEBUG) alertText("Driver does NOT have a signup time.");
	  }
	  if(($row['status'] == 0) && !checkQualified(1000)) {
	  	continue;
	  }

	  ?>
            <!-- Start <?=$description ?> Block -->
			<div align="center">
		     <table width="500" border="0" align="center">
			 <tr><TD>
			  <div style="padding: 5px;" align="center">
			   <fieldset>
			     <legend style="padding: 3px;  font-weight: bold;"><?= $description ?></legend>
				 <?php if(!$hasSignupTime) alertText("You do not have a signup time!"); ?>
<?php if( ( signupTime($signupid,$_SESSION['driver_id']) && $hasSignupTime && ($row['status'] == 2)) || ($row['status'] == 1) || (checkQualified(1000)) ) { ?>
				 <div align="center" style="padding: 3px; line-height: 120%; line-height: 120%;"><input type="button" onClick="location.href='<?= $_SERVER['PHP_SELF'] ?>?sched=pick_day&amp;group_id=<?=$group?><?php /*&signup_id=<?= $signupid ?> */?>'" value="Signup"></div>
<?php if($hasSignupTime) if( exclusiveAccess($signupid) && ENFORCE_EXCLUSION) {  // only run this command if they have a signup time, then if they have exclusive access, and it is enforced. ?>
				 <div align="center" style="padding: 3px; line-height: 120%; line-height: 120%;">You may gain exclusive access to the schedule for <?= floor(exclusiveAccess($signupid)/60) ?> minutes. <br><input type="button" onClick="location.href='<?= $_SERVER['PHP_SELF'] ?>?sched=pick_group&exclusive=<?= $signupid ?>'" value="Exclusive Access"></div>
<?php	} ?>
<?php } else { // allow them to view the schedule ?>
				 <div align="center" style="padding: 3px; line-height: 120%; line-height: 120%;"><A href="<?= $_SERVER['PHP_SELF'] ?>?sched=pick_day&amp;group_id=<?= $group ?><?php /*&signup_id=<?= $signupid ?> */?>">View Schedule</A></div>
<?php } ?>
<?php if( ($row['status'] == 2) && ENFORCE_EXCLUSION && exclusionActiveGroup($row['group_id']) ) { //if they are in schedule, exclusions are active, and an exclusion is set, display that.. ?>
				<div align="center" style="padding: 3px; line-height: 120%; color:#FF0000; font-weight:bold; "><?= driverName(exclusionActiveGroup($row['group_id'])) ?> has exclusive access until <?= exclusionActiveExpire($row['group_id']) ?>.</div>
<?php } ?>
				   <div align="center" style="padding: 3px; line-height: 120%; line-height: 120%;">Schedule Status: <span style="font-style: italic;"><?php
			switch ($row['status']) {
				case '0':
					echo "Closed";
					break;
				case '1':
					echo "Pending";
					break;
				case '2':
					echo "Schedule";
					break;
			} ?></span></div>
			  <?php if($row['status'] == 2) { 
			  
			  
			  ?>
				   <div align="center" style="padding: 3px; line-height: 120%; line-height: 120%;">Signup Time: <?php if($hasSignupTime) { echo date("l, F jS \a\\t g:i A",mktime(substr($time,0,2),substr($time,2,2),0,substr($date,4,2),substr($date,6,2),substr($date,0,4))); } else { print "None"; } ?></div>
				   <div class="highlight" align="center"><a href="?module=signup_sched&amp;group=<?= $group ?>">View Signup Schedule</a></div>
<div class="highlight" align="center"><a href="<?=$_SERVER['PHP_SELF']?>?module=rules&group_id=<?= $group ?>&amp;signupid=<?=$signupid?>">Read Signup Rules</a></div>
			  <?php } ?>
			   </fieldset>
			 </div>
			 </TD></tr>
			</table>
		</div>
<?php
	}
	mysql_free_result($sql);
  } else if($_REQUEST['sched'] == 'pick_day') {
	$driver = $_SESSION['driver_id'];
    //check if they've agreed to the signup rules
	$sql = sprintf("SELECT * FROM `t_sched_signups` WHERE `t_sched_signups`.`group_id` = %s AND `t_sched_signups`.`driver_id` = %s",quote_smart($_REQUEST['group_id']),$driver);
	$result = mysql_query($sql);
	if(DEBUG) alertText("SQL: $sql<br>\nResults returned for signup query: ". mysql_num_rows($result));
	if(mysql_num_rows($result) > 1) {
		errorText("More than one signup time exists for you. This may cause problems.");
		$hasSignupTime = true;
	} else if (mysql_num_rows($result) == 1) {
		$hasSignupTime = true;
	} else {
		errorText("You do not have a signup time for this schedule. You will not be able to signup for shifts!");
		$hasSignupTime = false;
	}
	
	//they have a signup time for this schedule... check if they've read the rules..
	if($hasSignupTime) {
		$signupdata = mysql_fetch_assoc($result);
		if($signupdata['accept_rules'] != 1) {
			//they didn't agree to the rules.. force them to agree!
			print "<div align='center'>You must first read and agree to the signup rules!</div>\n";
			print "<div align='center'><a href='" . $_SERVER['PHP_SELF'] . "?module=rules&amp;group_id=" . $signupdata['group_id'] . "&amp;signupid=" . $signupdata['signup_id'] . "'>Read the rules</a></div>\n";
			return;
		}
	}
	
	//////
	////
	//// BEGIN LISTING DAYS
	////
	//////
	
    print '<div align="center"><table width="600" align="center"><tr><td>' . "\n";
    //list all days available for current group
	$signup_id = $_REQUEST['signup_id'];
	$sql_statement = sprintf("SELECT `t_sched_groups`.`description`, `t_sched_groups`.`group_id` FROM `t_sched_groups` WHERE `t_sched_groups`.`group_id` = %s",quote_smart($_REQUEST['group_id']));
	$sql = mysql_query($sql_statement);
	printMYSQLDebug($sql_statement,$sql);
    $row = mysql_fetch_assoc($sql);
	$description = $row['description'];
	print "<h6>$description</h6>\n";
	mysql_free_result($sql);
	$group_id = $row['group_id'];
	$sql_statement = sprintf("SELECT `t_sched_main`.* 
					  FROM   `t_sched_main`, `t_sched_groups` 
					  WHERE  `t_sched_main`.`group_id` = `t_sched_groups`.`group_id` 
					  AND    `t_sched_groups`.`group_id` = %s 
					  ORDER BY `t_sched_main`.`order` ASC",$group_id);
	$sql = mysql_query($sql_statement);
	printMYSQLDebug($sql_statement,$sql);
	while($row = mysql_fetch_assoc($sql)) {
	  print "<div align='center'><a href='?sched=pick_shifts&tableid=" . $row['table_id'] . "'>" . $row['description'] .  "</a></div>\n";
	}
	print "</td></tr></table></div>\n";
	mysql_free_result($sql);
	
	//////
	////
	//// BEGIN LISTING LINES AND SHIFTS
	////
	//////	
  } else if($_REQUEST['sched'] == 'pick_shifts') {
  			  if(isset($_REQUEST['tableid']) && ($_REQUEST['tableid'] != '')) {
			  	  $table_sql = sprintf("SELECT * FROM `t_sched_main` WHERE `table_id` = %s",quote_smart($_REQUEST['tableid']));
				  $table_title = mysql_query($table_sql);
				  printMYSQLDebug($table_sql,$table_title);
				  if($table_title === false)
				  	printError("Error with SQL.",LVL_ERROR,"Error with title generating sql on pick shifts section of sched script.",1);
				  $row = mysql_fetch_assoc($table_title);
				  $scheduleDate = $row['description'];
				  ?>
					<div align="center"><table width="600" align="center"><tr><td>
					<h6 align="center">Schedule for <?= $scheduleDate ?></h6>
								 </td></tr></table>
					<?php
					  //determine next day and previous day for links at top of page
					  //previous
					  $sql = "SELECT * FROM `t_sched_main` WHERE `group_id` = " . $row['group_id'] . " AND `order` < " . $row['order'] . " ORDER BY `order` DESC LIMIT 1";
					  print "<!-- SQL: $sql -->";
					  $previous_result = mysql_query($sql);
					  if(mysql_num_rows($previous_result)) {
					    $prev_row = mysql_fetch_assoc($previous_result);
						$previousTable = $prev_row['table_id'];
					  } else {
					    $previousTable = false;
					  }
					  mysql_free_result($previous_result);
					  //next
					  $sql = "SELECT * FROM `t_sched_main` WHERE `group_id` = " . $row['group_id'] . " AND `order` > " . $row['order'] . " ORDER BY `order` ASC LIMIT 1";
					  print "<!-- SQL: $sql -->";
					  $next_result = mysql_query($sql);
					  if(mysql_num_rows($next_result)) {
					    $next_row = mysql_fetch_assoc($next_result);
						$nextTable = $next_row['table_id'];
					  } else {
					    $nextTable = false;
					  }
					  ?>
					  <div align="center">
					  <?php
					  //if there is a previous table, print back
					  if($previousTable) {
					    ?>
						<a href="<?= $_SERVER['PHP_SELF'] ?>?sched=pick_shifts&amp;tableid=<?= $previousTable ?><?php /* &amp;signup_id=<?= $_REQUEST['signup_id'] ?> */?>">&lt;&lt; Previous Day</a> | 
						<?php
					  }
						  ?> <a href="?sched=pick_day&amp;group_id=<?= $row['group_id'] ?>">List of Days</a> <?php
					  //if there is a next table, print next
					  if($nextTable) {
					    ?>
						| <a href="<?= $_SERVER['PHP_SELF'] ?>?sched=pick_shifts&amp;tableid=<?= $nextTable ?><?php /* &amp;signup_id=<?= $_REQUEST['signup_id'] ?> */?>">Next Day &gt;&gt;</a>
						<?php
					  }
					?>
					</div>
				  <?php generateShiftBoard($_REQUEST['tableid']); ?>
			 <div align="center">Schedule Updated at <?php echo date("H:i"); ?></div>
			 <div align="center">For an image key, <a href="?module=view_images">click here</a>.</div>
			 </div>
            	<?php
			  } else {
			  	print "Invalid Table ID!";
			  }
  }
  
  /* this is to allow for inclusion and marks the end of the sched part
    else {
    //display invalid option
	print "<p align='center'>Invalid option '" . $_REQUEST['sched'] . "'.</p>";
  }*/
  
 function printShiftImage($start,$end,$name,$type,$driver,$structure_id,$permission) {
 	// Gotta find out if they have a signup id.... only way is through the structure id.. :(
	$sql = "SELECT `t_sched_signups`.`signup_id`
			FROM `t_sched_structure`,`t_sched_main`,`t_sched_signups`
			WHERE `t_sched_structure`.`structure_id` = $structure_id
			  AND `t_sched_structure`.`table_id` = `t_sched_main`.`table_id`
			  AND `t_sched_main`.`group_id` = `t_sched_signups`.`group_id`
			  AND `t_sched_signups`.`driver_id` = " . $_SESSION['driver_id'] . "
			ORDER BY `date` ASC, `time` ASC LIMIT 1";
	$signup_result = @mysql_query($sql);
	if(@mysql_num_rows($signup_result) < 0) {
		printError("An error occured while searching for your signup time.");
	} else {
		$signup_id = mysql_fetch_assoc($signup_result);
		$signupid = $signup_id['signup_id'];
		if(DEBUG) alertText("Your signup time was found: $signupid");
	}
 
	// If the shift is open and they haven't had their signup time yet, make it unclickable
	if(($type == 'E') and ((signupTime($signupid,$_SESSION['driver_id']) or checkQualified(1000)) or ($_SESSION['is_dispatcher'] ==1))) {
		$type = 'O';
	}
    // If the shift is a covered driving shift, and the driver == logged in user, change type
    if(($driver == $_SESSION['driver_id']) && ($type == 'S'))
	    $type = 'M';
	
	//is ths shift open?? if so, print a link to sign up for it, but first check if they are allowed to drive it..
	if(($type == 'O') and checkQualified($permission))
		print '<a href="javascript:openShiftTaker(' . $structure_id . "," . $_REQUEST['tableid'] . "," . $_SESSION['driver_id'] . ",'" . $start . "','" . $end . "')\">";
	
	//do they want full size images?
	if($_REQUEST['fullsize'] == 1) {
		$fullsize = '&amp;fullsize=1';
		$fullsizeMD5 = '1';
	}
	// print image
	if(checkQualified($permission) or ($type != 'O')) {
		print "<img border=0 alt='$name' src='" . SHIFT_PNG_FOLDER . buildShiftImage($start , $name , $end , $type , $fullsizeMD5) . ".png'>";
	} else {
		print "<img border=0 alt='$name' src='" . SHIFT_PNG_FOLDER . buildShiftImage($start , $name , $end , 'X' , $fullsizeMD5) . ".png'>";
	}
	
	if(($type == 'O') and checkQualified($permission))
	   print "</a>";
 }

function buildShiftImage($s,$n,$e,$t,$f) {
//   ?start=" . $start . '&end=' . $end . "&name=" . $name . "&type=" . $type . $fullsize
	$filename = md5($s . $n . $e . $t . $f);
	if(!is_file(ROOT_SHIFT_PNG_FOLDER . $filename . '.png')) {
		//this file has not been created.. create on the fly!!
		$link = PNG_FILE . "?start=$s&end=$e&name=" . urlencode($n) . "&type=$t&fullsize=$f";		
		include($link);
		print "<!-- tried sending this link:  $link  -->";
	}
	return $filename;
}

	function generateShiftBoard($tableid) {
	
?>
		<!-- generateShiftBoard Function -->
			 <div align="center" style="margin: 5px">

			<script language="JavaScript" type="text/JavaScript">
			function openShiftTaker(structureID,tableID,driverID,previousEndTime,nextStartTime) {
<?php if(checkQualified(1000)) { //give them the bigger box ?>
				window.open('includes/takeShift.php?sid=' + structureID + '&tid=' + tableID + '&did=' + driverID + '&pet=' + previousEndTime + '&nst=' + nextStartTime,'takeshift','width=260,height=203,resizable=no,scrollbars=no,toolbars=no,location=no,directories=no,status=no,menubar=no')
<?php } else { // they aren't important enough for the big box.. throw em the small one ?>
				window.open('includes/takeShift.php?sid=' + structureID + '&tid=' + tableID + '&did=' + driverID + '&pet=' + previousEndTime + '&nst=' + nextStartTime,'takeshift','width=260,height=147,resizable=no,scrollbars=no,toolbars=no,location=no,directories=no,status=no,menubar=no')
<?php }  // end if ?>
			}
			</script>

			 
			 
			 <?php
			  //figure out earliest shift, so we can put fillers in front of any others
			  $earliest = 
			  		"SELECT `t_sched_structure`.`start` 
					 FROM   `t_sched_dates`,`t_sched_main`,`t_sched_structure` 
					 WHERE  `t_sched_main`.`table_id` = $tableid 
					 		AND `t_sched_main`.`table_id` = `t_sched_structure`.`table_id` 
					 ORDER BY `t_sched_structure`.`start` ASC LIMIT 1";
			  $earliest = mysql_query($earliest);
			  $earliest_row = mysql_fetch_assoc($earliest);
			  $day_start_time = $earliest_row['start'];
			  
			  //figure out latest shift, so we can put fillers on end of any others
			  $latest = mysql_query(
			  		"SELECT `t_sched_structure`.`end` 
					 FROM   `t_sched_dates`,`t_sched_main`,`t_sched_structure` 
					 WHERE  `t_sched_main`.`table_id` = $tableid 
					         AND `t_sched_main`.`table_id` = `t_sched_structure`.`table_id` 
					 ORDER BY `t_sched_structure`.`end` DESC LIMIT 1");
			  $latest_row = mysql_fetch_assoc($latest);
			  $day_end_time = $latest_row['end'];
			  
			  //calculate length of longest line in pixels
			  $daylength = subtractTime($day_end_time,$day_start_time);
			  $pixelLength = substr($daylength,0,2) * 60 + substr($daylength,2,2);
			  print "			 <table cellpadding=0 cellspacing=1 > \n";


			  $lines = mysql_query(
			  		"SELECT `t_sched_main`.`table_id`,`t_sched_structure`.* 
					 FROM   `t_sched_main`,`t_sched_structure` 
					 WHERE  `t_sched_main`.`table_id` = $tableid 
					        AND `t_sched_main`.`table_id` = `t_sched_structure`.`table_id` 
					 ORDER BY `t_sched_structure`.`order`");
			  while($line_info = mysql_fetch_assoc($lines)) {
			    $last_end = $line_info['start'];
				$end_time = $line_info['start'];
			    $structure_id = $line_info['structure_id'];
			 ?>
			  <tr> 
			   <td><img src="/images/<?= $line_info['image_file'] ?>" alt="<?= $line_info['description'] ?>"></td>
			   <td><?php
			         $line = $line_info['line'];
			         $result = mysql_query(
					 		"SELECT `t_sched_shifts`.`shift_id` , `t_sched_structure`.`structure_id`, 
							        `t_sched_structure`.`line` , `t_sched_shifts`.*, 
									`t_drivers`.`firstname` , `t_drivers`.`lastname` , 
									`t_sched_shifts`.`shift_start` , `t_sched_shifts`.`shift_end`, `t_drivers`.`nickname` 
							 FROM   `t_sched_main` , `t_sched_shifts` , `t_sched_structure` , `t_drivers` 
							 WHERE  `t_sched_main`.`table_id` = $tableid 
							 AND    `t_sched_main`.`table_id` = `t_sched_shifts`.`table_id`
							 AND    `t_sched_shifts`.`structure_id` = `t_sched_structure`.`structure_id`
							 AND    `t_sched_shifts`.`driver_id` = `t_drivers`.`driver_id` 
							 AND    `t_sched_structure`.`structure_id` = $structure_id 
							 ORDER BY `t_sched_shifts`.`shift_start` ASC");
			         $first = 1;

					 if($day_start_time < $line_info["start"]) { // print filler in front of line if necessary
						 printShiftImage($day_start_time,$line_info['start'],'','F',NULL,$structure_id,'0000'); 
					 }
			         while($shift = mysql_fetch_assoc($result)) {
			            if($first) {
						   //if($line_info['start'] 
						   if($shift['shift_start'] > $line_info['start']) { //we have an available opening shift
						      printShiftImage($line_info['start'],$shift['shift_start'],'','E','',$structure_id,$line_info['permissions']);
						   }
						   printShiftImage($shift['shift_start'],$shift['shift_end'],$shift['nickname'],'S',$shift['driver_id'],$structure_id,$line_info['permissions']);
			               $last_end = $shift['shift_end'];
			               $first = 0;
						   $end_time = $shift['shift_end'];
			               continue;
			            } else if ($shift['shift_start'] == $last_end) {
			               printShiftImage($shift["shift_start"],$shift["shift_end"],$shift['nickname'],'S',$shift['driver_id'],$line_info['structure_id'],$line_info['permissions']);
			               $last_end = $shift['shift_end'];
						   $end_time = $shift['shift_end'];
			               continue;
			            } else {
						   printShiftImage($last_end,$shift['shift_start'],'','E','',$line_info['structure_id'],$line_info['permissions']);
						   printShiftImage($shift['shift_start'],$shift['shift_end'],$shift['nickname'],'S',$shift['driver_id'],$line_info['structure_id'],$line_info['permissions']);
			               $last_end = $shift['shift_end'];
						   $end_time = $shift['shift_end'];
			               continue;
			            }
			         }
					 if($end_time < $line_info['end']) { //show the last bit of the shift as available!
			               printShiftImage($last_end,$line_info['end'],'','E','',$line_info['structure_id'],$line_info['permissions']);
						   $last_end = $line_info['end'];
						   $end_time = $line_info['end'];
					 }
					 if($end_time < $day_end_time) { //add filler to end of line
					    printShiftImage($end_time,$day_end_time,'','F','',$line_info['structure_id'],$line_info['permissions']);
					 }
			         mysql_free_result($result);
			 ?></td>
			  </tr>
			 <?php			 
			  }
			  mysql_free_result($lines);
			 ?>
			 </table>
			 </div>
		<?php
	}
	
	
	
	function exclusiveAccess ($signupId) { // grants exclusive access if the user qualifies..
		//grab data on this signup time
		$check1 = mysql_query("SELECT * FROM `t_sched_signups` WHERE `signup_id` = $signupId");
		$signup_info = mysql_fetch_assoc($check1);		
		
		//lets find out if they deserve exclusive access..
		//they can only get it once..  if exclusive = 1, they've already used it
		if($signup_info['exclusive'] == 1)
			return false;
		
		//check if they are within their signup time.. (after their time, before the next..)
		//after their time?
		if(signupTime($signupId,$_SESSION['driver_id'])) {
			//lets see if it's before the next time.. and if so, calculate exclusive access length
			$test_sql = "SELECT * FROM `t_sched_signups` WHERE `group_id` = " . $signup_info['group_id'] . " AND CONCAT( `date` , `time` ) > " . $signup_info['date'] . $signup_info['time'] . " ORDER BY `date` ASC, `time` ASC LIMIT 1";
			//print "<!-- $test_sql -->\n";
			$nextTime = mysql_query($test_sql);
			//if no response, they must be the last person.. ok for lock
			if(mysql_num_rows($nextTime) == 0) {
				//no limit.. give 'em 30 minutes
				//print "<!-- no time limit -->\n";
				return 30 * 60; 
			} else {
				//there is another shift after.. find out how long
				$nextTime_info = mysql_fetch_assoc($nextTime);
				//is their signup time valid?
				if(signupTime($nextTime_info['signup_id'],$nextTime_info['driver_id'])) {
					//the next drivers time has come.. they can't get exclusive
					return false; 
				} else {
					//the next drivers time hasn't come.. calculate exclusiveness
					$date = $nextTime_info['date'];
					$time = $nextTime_info['time'];
					$next_signup_time = mktime(substr($time,0,2),substr($time,2,2),0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
					//print "<!-- next signup = $next_signup_time -->\n";
					$thirtyMinutes = 30 * 60 + time();
					//print "<!-- thirty minutes = $thirtyMinutes -->\n";
					if($next_signup_time > $thirtyMinutes) {
						return 30 * 60;
					} else {
						return $next_signup_time - time();
					}
				}
			}
		}
	}
?> 